package com.example.cloudmusic


import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.example.cloudmusic.community.CommunityFragment
import com.example.cloudmusic.databinding.ActivityMainBinding
import com.example.cloudmusic.discover.DiscoverFragment
import com.example.cloudmusic.home.HomeFragment
import com.example.cloudmusic.live.LiveFragment
import com.example.cloudmusic.profile.ProfileFragment
import com.example.cloudmusic.utils.PermissionUtil
import com.example.cm_utils.ToastUtil
import com.example.cm_base.BaseActivity
import com.example.cm_player.activity.PlayerActivity
import com.example.cm_player.manager.PlayerStateManager


class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>() {
    private var currentBackPressedTime = 0L
    private val BACK_PRESSED_INTERVAL = 2000
    private var contentId = -1
    private var homeFragment: HomeFragment? = null
    private var profileFragment: ProfileFragment? = null
    private var discoverFragment: DiscoverFragment? = null
    private var liveFragment: LiveFragment? = null
    private var lastShowFragment: Fragment? = null
    private var communityFragment: CommunityFragment? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        PermissionUtil.checkPushPermission(this)
        initView()
        viewModel.bindPlayerService()
    }


    override fun initObservers() {
        PlayerStateManager.currentPlayedMusic.observe(this) {
            if (it != null) {
                binding.cmSongTitle.text = it.title
                binding.cmMiniSongArtist.text = it.artist
                Glide.with(binding.root)
                    .load(it.imageUrl)
                    .error(R.drawable.ic_music)
                    .circleCrop()  // 使用Glide的圆形裁剪功能
                    .into(binding.cmMiniAlbumArt)
            }
        }

        PlayerStateManager.isPlaying.observe(this) {
            if (it) {
                if (binding.cmMiniPlayer.visibility == View.GONE) {
                    binding.cmMiniPlayer.visibility = View.VISIBLE
                }
                binding.cmMiniPlayPauseButton.setImageResource(R.drawable.ic_pause)
            } else {
                binding.cmMiniPlayPauseButton.setImageResource(R.drawable.ic_play)
            }
        }
    }

    @SuppressLint("CommitTransaction")
    private fun initView() {
        contentId = binding.cmFragmentContainer.id

        initFirstFragment()

        binding.cmMenuButton.setOnClickListener {
            binding.cmDrawerLayout.open()
        }

        binding.cmMiniPlayer.setOnClickListener {
            startActivity(Intent(this, PlayerActivity::class.java))
        }

        binding.cmMiniPlayPauseButton.setOnClickListener {
            if (PlayerStateManager.isPlaying.value == true) {
                viewModel.pause()
            } else {
                viewModel.resume()
            }
        }

        binding.cmMiniPlaylistButton.setOnClickListener {
            MusicListDialog().apply {
                removeMusicCallback = {
                    viewModel.removeFromPlaylist(it)
                }
                changeMusicCallback = {
                    viewModel.playSong(it)
                }
                show(supportFragmentManager, null)
            }
        }

        setupDrawerMenuListeners()

        binding.cmBottomNavigation.setOnItemSelectedListener { item ->
            if (item.itemId != binding.cmBottomNavigation.selectedItemId) {
                when (item.itemId) {
                    R.id.nav_home -> {
                        showFragment(homeFragment!!)
                    }

                    R.id.nav_discover -> {
                        if (discoverFragment == null) {
                            discoverFragment = DiscoverFragment()
                            supportFragmentManager.beginTransaction()
                                .add(contentId, discoverFragment!!, "DiscoverFragment")
                                .commit()
                        }
                        showFragment(discoverFragment!!)
                    }

                    R.id.nav_live -> {
                        if (liveFragment == null) {
                            liveFragment = LiveFragment()
                            supportFragmentManager.beginTransaction()
                                .add(contentId, liveFragment!!, "LiveFragment")
                                .commit()
                        }
                        showFragment(liveFragment!!)
                    }

                    R.id.nav_profile -> {
                        if (profileFragment == null) {
                            profileFragment = ProfileFragment()
                            supportFragmentManager.beginTransaction()
                                .add(contentId, profileFragment!!, "ProfileFragment")
                                .commit()
                        }
                        showFragment(profileFragment!!)
                    }

                    R.id.nav_community -> {
                        if (communityFragment == null) {
                            communityFragment = CommunityFragment()
                            supportFragmentManager.beginTransaction()
                                .add(contentId, communityFragment!!, "CommunityFragment")
                                .commit()
                        }
                        showFragment(communityFragment!!)
                    }
                }
                return@setOnItemSelectedListener true
            }
            false
        }
    }


    private fun setupDrawerMenuListeners() {
        // 用户信息区域点击事件 - 跳转到登录页
        binding.cmDrawerView.cmUserAvatar.setOnClickListener {
            Toast.makeText(this, "跳转到登录页面", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // VIP会员卡点击事件
        binding.cmDrawerView.cmVipCard.setOnClickListener {
            Toast.makeText(this, "开通黑胶VIP", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 扫一扫按钮点击事件
        binding.cmDrawerView.cmScanQrButton.setOnClickListener {
            Toast.makeText(this, "打开扫一扫", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 消息中心点击事件
        binding.cmDrawerView.cmMessagesOption.setOnClickListener {
            Toast.makeText(this, "进入消息中心", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 云村有票点击事件
        binding.cmDrawerView.cmTicketsOption.setOnClickListener {
            Toast.makeText(this, "进入云村有票", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 商城点击事件
        binding.cmDrawerView.cmShopOption.setOnClickListener {
            Toast.makeText(this, "进入商城", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 游戏专区点击事件
        binding.cmDrawerView.cmGameOption.setOnClickListener {
            Toast.makeText(this, "进入游戏专区", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 设置点击事件
        binding.cmDrawerView.cmSettingsOption.setOnClickListener {
            Toast.makeText(this, "进入设置", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 夜间模式点击事件
        binding.cmDrawerView.cmNightModeOption.setOnClickListener {
            // 切换夜间模式开关
            binding.cmDrawerView.cmNightModeSwitch.isChecked =
                !binding.cmDrawerView.cmNightModeSwitch.isChecked
            val mode = if (binding.cmDrawerView.cmNightModeSwitch.isChecked) "开启" else "关闭"
            Toast.makeText(this, "夜间模式${mode}", Toast.LENGTH_SHORT).show()
        }

        // 定时关闭点击事件
        binding.cmDrawerView.cmTimerOption.setOnClickListener {
            Toast.makeText(this, "设置定时关闭", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }

        // 音乐闹钟点击事件
        binding.cmDrawerView.cmAlarmOption.setOnClickListener {
            Toast.makeText(this, "设置音乐闹钟", Toast.LENGTH_SHORT).show()
            binding.cmDrawerLayout.close()
        }
    }

    private fun showFragment(fragmentToShow: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.show(fragmentToShow)
        lastShowFragment?.let {
            transaction.hide(it)
        }
        lastShowFragment = fragmentToShow
        transaction.commit()
    }

    @SuppressLint("CommitTransaction")
    private fun initFirstFragment() {
        homeFragment = HomeFragment()
        supportFragmentManager.beginTransaction()
            .add(contentId, homeFragment!!, "HomeFragment")
            .commit()
        lastShowFragment = homeFragment
    }

    override fun onBackPressed() {
        if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
            currentBackPressedTime = System.currentTimeMillis()
            ToastUtil.show("再按一次退出")
            return
        }
        super.onBackPressed()
    }


    override fun onDestroy() {
        super.onDestroy()
        viewModel.unbindPlayerService()
        (application as CloudMusicApplication).releaseResources()
    }


}

